// components/pull-refresh/pull-refresh.js
Component({
  options: {
    styleIsolation: 'apply-shared'
  },
  /**
   * 组件的属性列表
   */
  properties: {
    refresh: Boolean
  },

  /**
   * 组件的初始数据
   */
  data: {
    refreshIconTop: -80,
    refreshIconOpacity: 0.5,
    refreshIconRotate: 0,
    hasTransition: false,
    hasAnimation: false,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    handlePullStart(e) {
      this.startY = e.changedTouches[0].pageY;
      this.setData({
        hasTransition: false,
        hasAnimation: false,
        refreshIconTop: -80,
        refreshIconOpacity: 0.5,
        refreshIconRotate: 0,
      })
      this.triggerEvent('refreshstart')
      this.move = false;
    },
    handlePulling(e) {
      this.move = true;
      const endY = e.changedTouches[0].pageY
      let distance = endY - this.startY - 80;
      
      // 下拉的最大值
      if (distance > 200) {
        distance = 200
      }
      this.distance = distance;

      if (distance < -80) return;
      // 透明度变化。从0.5开始才能看到效果
      let opacity = distance / 200 + 0.5
      opacity = opacity > 1 ? 1 : opacity;
      // 旋转：-80 - 100 旋转更多 720deg  100 - 200 旋转更少 360deg
      let rotate
      if (distance <= 100) {
        rotate = distance * 720 / 100
      } else {
        rotate = distance * 360 / 100
      }
     
      this.setData({
        refreshIconTop: distance,
        refreshIconOpacity: opacity,
        refreshIconRotate: rotate
      })
    },
    handlePullEnd() {
      if (!this.move) return;

      if (this.distance < 100) {
        this.setData({
          refreshIconTop: -80,
          hasTransition: true,
        })
        return;
      }
      this.setData({
        refreshIconTop: 100,
        hasTransition: true,
        hasAnimation: true
      })
      this.triggerEvent('refreshing');
    },
  }
})
